package com.yyf.hap.sale.controllers;

import com.hand.hap.core.web.view.ui.Model;
import com.yyf.hap.sale.utils.DateUtil;
import org.apache.http.ParseException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import com.hand.hap.system.controllers.BaseController;
import com.hand.hap.core.IRequest;
import com.hand.hap.system.dto.ResponseData;
import com.yyf.hap.sale.dto.Manage;
import com.yyf.hap.sale.service.IManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.beans.IntrospectionException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ManageController extends BaseController {

	@Autowired
	private IManageService service;


	@RequestMapping(value = "/salary/manage/query")
	@ResponseBody
	public ResponseData query(Manage dto, @RequestParam(defaultValue = DEFAULT_PAGE) int page,
							  @RequestParam(defaultValue = DEFAULT_PAGE_SIZE) int pageSize, HttpServletRequest request) {
		IRequest requestContext = createRequestContext(request);
		return new ResponseData(service.select(requestContext, dto, page, pageSize));
	}

	@RequestMapping(value = "/salary/manage/submit")
	@ResponseBody
	public ResponseData update(@RequestBody List<Manage> dto, BindingResult result, HttpServletRequest request) {
		getValidator().validate(dto, result);
		if (result.hasErrors()) {
			ResponseData responseData = new ResponseData(false);
			responseData.setMessage(getErrorMessage(result, request));
			return responseData;
		}
		IRequest requestCtx = createRequestContext(request);
		return new ResponseData(service.batchUpdate(requestCtx, dto));
	}

	@RequestMapping(value = "/salary/manage/remove")
	@ResponseBody
	public ResponseData delete(HttpServletRequest request, @RequestBody List<Manage> dto) {
		service.batchDelete(dto);
		return new ResponseData();
	}

	/**
	 * 导入
	 *
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/import")
	public String impotr(HttpServletRequest request, Model model) throws Exception {
		long adminId = 1;
		//获取上传的文件
		MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
		MultipartFile file = multipart.getFile("upfile");
		if (file.isEmpty()) {
			JOptionPane.showMessageDialog(null, "上传文件为空！", "错误", JOptionPane.ERROR_MESSAGE);
			return "Faiure";
		}
		//String month = request.getParameter("month");
		String month = "5";
		InputStream in = file.getInputStream();
		//数据导入
		service.importExcelInfo(in, file, month, adminId);
		in.close();
		//return "redirect:/salary/index.html";
		return "OK";
	}

	/**
	 * Excel 导出
	 *
	 * @param request
	 * @param response
	 * @throws ClassNotFoundException
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws ParseException
	 * @throws InvocationTargetException
	 */
	@RequestMapping("/salary/excel/export")
	public @ResponseBody
	void export(HttpServletRequest request, HttpServletResponse response)
			throws ClassNotFoundException, IntrospectionException, IllegalAccessException, ParseException, InvocationTargetException, UnsupportedEncodingException {

		response.reset(); //清除buffer缓存
		Map<String, Object> map = new HashMap<String, Object>();
		String nowTime = DateUtil.dateToString(new Date());
		String fileName = "yyf_order_" + nowTime;
		// 指定下载的文件名，浏览器都会使用本地编码，即GBK，浏览器收到这个文件名后，用ISO-8859-1来解码，然后用GBK来显示
		// 所以我们用GBK解码，ISO-8859-1来编码，在浏览器那边会反过来执行。
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1")+".xlsx");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		XSSFWorkbook workbook = null;
		//导出Excel对象
		workbook = service.exportExcelInfo();
		OutputStream output = null;
		try {
			output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
			bufferedOutPut.flush();
			workbook.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}